<?php
namespace Little\Controller;
use Think\Controller;
use Think\Image;

//**********************二维码****************************

class CodesController extends Controller{
    //生成二维码
    public function index(){
        $code         = I('code');
        $user         = users("users","id,headimgurl,nickname",$code);
        $access_token = getAccessToken();
        $scene        = $user['id'];
        $width        = 430;
        $auto_color   = true;
        $line_color   = '{"r":"0","g":"0","b":"0"}';

        $filePath = "Data/codes/{$scene}.png";

        //拼接图片
        $image = new \Think\Image();
        //图片是否存在
        if(!file_exists($filePath)) //false
        {
            $url      = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token;
            $se       = $scene;
            $arr      = json_encode(array("scene"=>$se,"page"=>'pages/index/index'));//必须是已经上线的 页面
            $data         = httpPost($url,$arr);
            //生成图片
            $imgDir =  'Data/codes/';
            $filename= $scene.".png";///要生成的图片名字
            $xmlstr =  $data;
            if(empty($xmlstr)) {
                $xmlstr = file_get_contents('php://input');
            }

            $jpg = $xmlstr;//得到post过来的二进制原始数据
            if(empty($jpg))
            {
                echo 'nostream';
                exit();
            }else{
                $file = fopen("./".$imgDir.$filename,"w");//打开文件准备写入
                fwrite($file,$jpg);//写入
                fclose($file);//关闭
                //获取用户头像
                $img=file_get_contents($user['headimgurl']);
                $a = file_put_contents("Data/test/logo.png",$img);

                $image = new \Think\Image();

                //压缩
                $image->open("Data/test/logo.png")->thumb(100, 100)->save('Data/test/logo.png');//用户头像
                //$image->open("Data/test/er.png")->thumb(500, 500)->save('Data/test/er.png');
                //添加水印
                $image->open("Data/test/zhu.png")->water("Data/test/logo.png",array(30,30))->save("Data/test/wan.png");
                $image->open("Data/test/wan.png")->water("Data/codes/{$filename}",\Think\Image::IMAGE_WATER_CENTER)->save("Data/test/wan.png"); //二维码
                // 在图片添加水印文字
                $image->open("Data/test/wan.png")->text($user['nickname'],'Data/test/wryh.ttf',20,'#373634',array(160,70))->save("Data/codes/{$filename}");
                $ai = IMGS."Data/codes/{$filename}";
                echo json_encode(array("do"=>$ai,"user_id"=>$user['id']));
            }
        }else{
            $ai = IMGS.$filePath;
            echo json_encode(array("do"=>$ai,"user_id"=>$user['id']));
        }
    }
}